package com.ants.platform.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * BASE64 （可逆加密 常用于登入用户token加密）
 * MD5 、SHA 、HMAC （非可逆加密）
 * Created by xiang.li on 2015/2/27.
 */
public class StringEncryptUtil {

    private static final Logger logger = LoggerFactory.getLogger(StringEncryptUtil.class);
    // 密钥
    private final static String secretKey = "liushun#ants@lx100$#365#$";
    // 向量
    private final static String iv = "01234567";
    // 加解密统一使用的编码方式
    private final static String encoding = "utf-8";

    private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * MD5加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String MD5(String data) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(data.getBytes());
            // 获得密文
            byte[] result = md5.digest();
            // 把密文转换成十六进制的字符串形式
            int j = result.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte b = result[i];
                str[k++] = hexDigits[b >>> 4 & 0xf];
                str[k++] = hexDigits[b & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            logger.error("MD5加密失败!", e.getMessage());
            return null;
        }
    }


    // 加密
    public static String encBase64(byte[] b) {
        return new BASE64Encoder().encode(b);
    }

    // 解密
    public static byte[] decBase64(String s) {
        byte[] result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                result = decoder.decodeBuffer(s);
            } catch (Exception e) {
                logger.error("Base64解密失败!", e.getMessage());
            }
        }
        return result;
    }


    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     * @return
     * @throws Exception
     */
    public static String encode(String plainText) {
        Key deskey = null;
        DESedeKeySpec spec = null;
        String result = "";
        try {
            spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
            byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
            result = encBase64(encryptData);
        } catch (Exception e) {
            logger.error("3Des加密失败!", e.getMessage());
        }

        return result;
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return
     * @throws Exception
     */
    public static String decode(String encryptText) {
        Key deskey = null;
        DESedeKeySpec spec = null;
        String result = "";
        try {
            spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
            byte[] decryptData = cipher.doFinal(decBase64(encryptText));
            result = new String(decryptData, encoding);
        } catch (Exception e) {
            logger.error("3Des解密失败!", e.getMessage());
            return "";
        }
        return result;
    }
}